import { getSignature } from "@/api/index.js";
import OSS from "ali-oss";
import { getUrlParams } from "./tools.js";
/**
 * 处理oss的region和bucket
 * @param {*} url
 * @returns
 */
function extractSpecificParts(url) {
  const parts = url.split("/");
  const domainParts = parts[2].split(".");
  const bucketName = domainParts[0];
  const region = domainParts[1];
  return { bucketName, region };
}
/**
 * 文件上传
 * @param {*} file
 * @returns
 */
export const putFile = async (file) => {
  const { data } = await getSignature({ fileName: file.name });
  console.log(data);
  //处理url?
  let obj = getUrlParams(data.url);
  let conf = extractSpecificParts(data.url);
  let config = {
    region: conf.region,
    secure: false, // secure: 配合region使用，如果指定了secure为true，则使用HTTPS访问
    accessKeyId: obj.OSSAccessKeyId,
    accessKeySecret: obj.Signature,
    bucket: conf.bucketName,
  };
  let client = new OSS(config);
  let objectKey = file.lastModified + "_" + file.name;
  console.log(file);
  //异步返回链接
  return new Promise((resolve, reject) => {
    client
      .multipartUpload(objectKey, file)
      .then((result) => {
        resolve({
          code: 0,
          url:
            "https://" +
            config.bucket +
            "." +
            config.region +
            ".aliyuncs.com/" +
            objectKey,
          msg: "ok",
        });
      })
      .catch((err) => {
        console.log(err);
        reject({ code: -1, url: "", msg: "上传出错了" });
      });
  });
};
